/*
 *  Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package ru.apertum.qsystem.client.forms;

import javax.swing.JDialog;
import lombok.extern.log4j.Log4j2;
import org.jdesktop.application.Action;
import ru.apertum.qsystem.common.Uses;
import ru.apertum.qsystem.server.model.QService;
import ru.apertum.qsystem.server.model.QServiceTree;
import ru.apertum.qsystem.server.model.QUser;

import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.LayoutStyle;
import javax.swing.ListModel;
import javax.swing.WindowConstants;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.ResourceBundle;

/**
 * Created on 16.10.2009, 19:35:45.
 *
 * @author Evgeniy Egorov
 */
@SuppressWarnings({"squid:S1192", "squid:S1172", "squid:S1450", "squid:S1604", "squid:S1161", "squid:MaximumInheritanceDepth"})
@Log4j2
public class FMessager extends javax.swing.JDialog {

    /**
     * Creates new form FMessager.
     */
    public FMessager(java.awt.Frame parent, boolean modal, int port, ListModel<QUser> users, TreeModel services) {
        super(parent, modal);
        initComponents();
        this.port = port;
        listUsers.setModel(users);
        treeServices.setModel(services);
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    private void initComponents() {
        ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.client.forms.resources.FMessager");
        jPanel1 = new JPanel();
        jLabel1 = new JLabel();
        checkBoxAll = new JCheckBox();
        jSplitPane1 = new JSplitPane();
        jScrollPane2 = new JScrollPane();
        listUsers = new JList<>();
        jScrollPane3 = new JScrollPane();
        treeServices = new JTree();
        jPanel2 = new JPanel();
        jScrollPane1 = new JScrollPane();
        textAreaMessage = new JTextArea();
        buttonSend = new JButton();
        sendMessageAction = new SendMessageAction();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(bundle.getString("Form.title"));
        setName("Form");
        var contentPane = getContentPane();

        //======== jPanel1 ========
        {
            jPanel1.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
            jPanel1.setName("jPanel1");

            //---- jLabel1 ----
            jLabel1.setText(bundle.getString("jLabel1.text"));
            jLabel1.setName("jLabel1");

            //---- checkBoxAll ----
            checkBoxAll.setText(bundle.getString("checkBoxAll.text"));
            checkBoxAll.setName("checkBoxAll");

            GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup()
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
                        .addComponent(checkBoxAll)
                        .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup()
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(checkBoxAll))
                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
        }

        //======== jSplitPane1 ========
        {
            jSplitPane1.setDividerLocation(155);
            jSplitPane1.setName("jSplitPane1");

            //======== jScrollPane2 ========
            {
                jScrollPane2.setName("jScrollPane2");

                //---- listUsers ----
                listUsers.setBorder(new TitledBorder(bundle.getString("listUsers.border.title")));
                listUsers.setName("listUsers");
                jScrollPane2.setViewportView(listUsers);
            }
            jSplitPane1.setLeftComponent(jScrollPane2);

            //======== jScrollPane3 ========
            {
                jScrollPane3.setName("jScrollPane3");

                //---- treeServices ----
                treeServices.setBorder(new TitledBorder(bundle.getString("treeServices.border.title")));
                treeServices.setName("treeServices");
                jScrollPane3.setViewportView(treeServices);
            }
            jSplitPane1.setRightComponent(jScrollPane3);
        }

        //======== jPanel2 ========
        {
            jPanel2.setBorder(new TitledBorder(bundle.getString("jPanel2.border.title")));
            jPanel2.setName("jPanel2");

            //======== jScrollPane1 ========
            {
                jScrollPane1.setName("jScrollPane1");

                //---- textAreaMessage ----
                textAreaMessage.setColumns(20);
                textAreaMessage.setRows(5);
                textAreaMessage.setName("textAreaMessage");
                jScrollPane1.setViewportView(textAreaMessage);
            }

            GroupLayout jPanel2Layout = new GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup()
                    .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup()
                    .addComponent(jScrollPane1, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
            );
        }

        //---- buttonSend ----
        buttonSend.setName("buttonSend");
        buttonSend.setAction(sendMessageAction);
        buttonSend.setText(bundle.getString("sendMessage.Action.text"));
        buttonSend.setToolTipText(bundle.getString("sendMessage.Action.shortDescription"));

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
                    .addContainerGap(248, Short.MAX_VALUE)
                    .addComponent(buttonSend)
                    .addContainerGap())
                .addComponent(jPanel2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSplitPane1, GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSplitPane1, GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jPanel2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(buttonSend)
                    .addContainerGap())
        );
        pack();
        setLocationRelativeTo(getOwner());
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Используемая ссылка на диалоговое окно.
     */
    private static FMessager messagerForm;
    private final int port;

    /**
     * Выбор услуги для перенаправления.
     */
    public static void getMessager(JFrame owner, int port, ListModel<QUser> users, TreeModel services) {
        log.info("Выбор услуги для перенаправления.");
        if (messagerForm == null) {
            messagerForm = new FMessager(owner, true, port, users, services);
        }
        messagerForm.setLocation((owner.getLocation().x + owner.getWidth() / 2 - messagerForm.getWidth() / 2),
                (owner.getLocation().y + owner.getHeight() / 2 - messagerForm.getHeight() / 2));
        messagerForm.setVisible(true);
    }

    /**
     * Отослать сообщение.
     */
    @Action
    public void sendMessage() {
        final StringBuilder message = new StringBuilder("message#");
        if (checkBoxAll.isSelected()) {
            message.append("ALL");
        } else {
            listUsers.getSelectedValuesList().forEach(o ->
                    message.append("@").append(o.getId().toString()).append("@")
            );
            if (treeServices.getSelectionPaths() != null) {
                for (TreePath selectedPath : treeServices.getSelectionPaths()) {
                    final QService service = (QService) selectedPath.getLastPathComponent();
                    QServiceTree.sailToStorm(service, (TreeNode service1) ->
                            message.append("@").append(((QService) service1).getId().toString()).append("@")
                    );
                }
            }
        }
        Uses.sendUDPBroadcast(message + "##" + textAreaMessage.getText(), port);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner non-commercial license
    private JPanel jPanel1;
    private JLabel jLabel1;
    private JCheckBox checkBoxAll;
    private JSplitPane jSplitPane1;
    private JScrollPane jScrollPane2;
    private JList<QUser> listUsers;
    private JScrollPane jScrollPane3;
    private JTree treeServices;
    private JPanel jPanel2;
    private JScrollPane jScrollPane1;
    private JTextArea textAreaMessage;
    private JButton buttonSend;
    private SendMessageAction sendMessageAction;
    // End of variables declaration//GEN-END:variables

    private class SendMessageAction extends AbstractAction {
        private SendMessageAction() {
            // JFormDesigner - Action initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
            // Generated using JFormDesigner non-commercial license
            ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.client.forms.resources.FMessager");

            putValue(NAME, bundle.getString("FMessager.sendMessageAction.Name"));
            // JFormDesigner - End of action initialization  //GEN-END:initComponents
        }

        public void actionPerformed(ActionEvent e) {
            sendMessage();
        }
    }
}
